layui.define(['jdhp'], function (exports) {
    function design_vi_main(args) {
        if (window.jdiyAdmin === undefined) window.jdiyAdmin = {};
        let body = $('body'),
            $g = s => $('#' + s + '_' + args.uid),
            canvas = $g('viCanvas'),
            rtForm = $g('inProps'),
            divTds = $g('vi_tdsDiv'),
            divBtn0 = $g('btn0Div'),
            $gs = function (s, h = []) {
                if (s.length) for (let i = s.length; i--;) $g(s[i]).show();
                if (h.length) for (let i = h.length; i--;) $g(h[i]).hide();
            },
            $selected = () => ({
                t: canvas.find('.jdiy-selected'),
                d: eData[canvas.find('.jdiy-selected').attr('id').substring(10)]
            }),
            $selBtn = () => {
                let t = canvas.find('.jdiy-selected');
                return {t: t, d: sBtns[t.attr('id').substring(10)]}
            },
            $selTab = () => {
                let t = canvas.find('.jdiy-selected');
                return {t: t, d: sTabs[t.attr('id').substring(10)]}
            },
            fillOpts = (o, pleaseText, items, selVal, jgFunc = (it) => it) => {
                let sa = pleaseText === false ? [] : ['<option value="">' + pleaseText + '</option>'];
                for (let i = 0; i < items.length; i++) {
                    let [v, k] = jgFunc(items[i]);
                    sa.push('<option value="' + v + '"' + (String(v) === String(selVal) ? ' selected' : '') + '>' + k + '</option>');
                }
                return o.html(sa.join(''));
            },
            selectOn = function (a, b) {
                layui.form.on('select(' + a + '_' + args.uid + ')', b);
            },
            switchOn = function (a, b) {
                layui.form.on('switch(' + a + '_' + args.uid + ')', b);
            },
            sData = {},
            sBtns = {},
            sTabs = {},
            eData = [],
            addNewId = 1,
            btnTypes = [
                ['edit', '修改'],
                ['del', '删除'],
                ['update', '更新字段值'],
                ['exec', '执行增强代码'],
                ['ajax', '执行自定义ajax请求'],
                ['page', '打开系统界面'],
                ['link', '打开自定义页面']
            ],
            formatTds = function () {
                let r, e, ri = 0, ci, tds = [];
                canvas.find('.layui-form-item').each(function () {
                    r = $(this).find('.vitxt');
                    if (r.length > 0) {
                        ci = 0;
                        r.each(function () {
                            e = eData[$(this).attr('id').substring(10)];
                            e.row = ri;
                            e.col = ci++;
                            tds.push(e);
                            if (ci === 2) ri++;
                        });
                        ri++;
                    }
                });
                sData.tds = tds;
            },
            setOpacity = function (o, v) {
                if (o.hasClass('col')) {
                    let index = o.index() + 1;
                    canvas.find('.jdiy-ls-design-tb thead th:nth-child(' + index + ')').css({opacity: v});
                    canvas.find('.jdiy-ls-design-tb tbody td:nth-child(' + index + ')').css({opacity: v});
                } else {
                    o.css({opacity: v});
                }
                return o;
            },
            getLineCss = (t) => {
                if (t.hasClass('col')) {
                    let index = t.index() + 1,
                        o1 = canvas.find('.jdiy-ls-design-tb thead th:nth-child(' + index + ')'),
                        o2 = canvas.find('.jdiy-ls-design-tb tbody td:nth-child(' + index + ')');
                    return {
                        width: '3px',
                        height: (o1.outerHeight() + o2.outerHeight() + 2) + 'px',
                        top: (o1.offset().top) + 'px'
                    }
                } else {
                    return {width: '3px', height: t.outerHeight() + 'px', top: (t.offset().top) + 'px'}
                }
            },
            startDrag = function (e, dragThis) {
                body.addClass('drag-move');
                jdiyAdmin.inDesign.dragging = true;
                jdiyAdmin.inDesign.dragThis = dragThis.css({opacity: 0.1});
                jdiyAdmin.inDesign.mouse = {x: e.clientX, y: e.clientY};
            },
            footerBtnShow = function (d) {
                if (d.footer === undefined || d.footer === null) d.footer = true;
                if (d.act === 'link' && d.target === 'dialog') {
                    $g('btn_footerDiv').show();
                    $g('btn_footer').prop('checked', d.footer);
                    layui.form.render(null, rtForm.attr('id'));
                }
            },
            loadFields = function (e, et, s) {
                !et ? s({code: 200, data: []}) :
                    $.ajax({
                        url: jdiyAdmin.ctx + '/mgmt/JDiyAdmin/ui.' + (e ? 'fields?entity=' : 'columns?table=') + et,
                        success: s
                    });
            },
            joinTableOn = function (o) {
                let {d} = $selected();
                d.joinTable = o.value;
                loadFields(false, o.value, function (r) {
                    fillOpts($g('joinField'), '请选择外联显示字段', r.data, d.joinField, (it) => [
                        it[0], it[0] + '　- ' + it[1]
                    ]);
                    fillOpts($g('joinRef'), '请选择外键字段', r.data, d.joinRef, (it) => [
                        it[0], it[0] + '　- ' + it[1]
                    ]);
                    layui.form.render('select', rtForm.attr('id'));
                });
            },
            manyTableOn = function (o) {
                let {d} = $selected();
                d.manyTable = o.value;
                loadFields(false, o.value, function (r) {
                    fillOpts($g('manyField0'), '正向关联本表字段', r.data, d.manyField0, (it) => [
                        it[0], it[0] + '　- ' + it[1]
                    ]);
                    fillOpts($g('manyField1'), '反向关联外表字段', r.data, d.manyField1, (it) => [
                        it[0], it[0] + '　- ' + it[1]
                    ]);
                    layui.form.render('select', rtForm.attr('id'));
                });
            },
            propRender = {
                nul: function () {
                    rtForm.find('.ls-tpl_' + args.uid).hide();
                    $gs(['nulPropDiv']);
                    layui.element.tabChange('rtTab_' + args.uid, 'rtTab1_' + args.uid);
                },
                tds: function (d) {
                    rtForm.find('.ls-tpl_' + args.uid).hide();
                    $gs(['in_propAllDiv'], ['nulPropDiv']);
                    $('#in_propAllDiv_' + args.uid + '>.layui-form-item').hide();
                    let set = builder.propSet, so = function (some) {
                        let sa = some.split('|');
                        for (let i = sa.length; i--;) set[sa[i]](d[sa[i]], d);
                    };
                    $gs(['typesDiv', 'joinTypesDiv'], ['dictIdDiv', 'kvDiv', 'treesDiv', 'tplDiv']);
                    so('field|label');

                    if (d.joinType && d.joinType !== 'none') {
                        $gs(['outJoinDiv']);
                        let o = $g('joinTable');
                        try {
                            o.val(d.joinTable || '');
                        } catch (e) {
                            o.val('');
                        }
                        if (d.joinType === 'manyToOne') {
                            console.log('XXXXXXXX');
                            joinTableOn({value: o.val()});
                            $gs([], ['manyTableDiv', 'manyField0Div', 'manyField1Div', 'joinRefDiv']);
                        } else if (d.joinType === 'manyToMany') {
                            joinTableOn({value: o.val()});
                            $gs(['manyTableDiv', 'manyField0Div', 'manyField1Div'], ['joinRefDiv']);
                            $g('manyTable').val(d.manyTable || '');
                            manyTableOn({value: d.manyTable || ''});
                        } else if (d.joinType === 'oneToMany') {
                            joinTableOn({value: o.val()});
                            $gs(['joinRefDiv'], ['manyTableDiv', 'manyField0Div', 'manyField1Div']);
                        }
                    } else {
                        $gs([], ['outJoinDiv', 'joinRefDiv', 'manyTableDiv', 'manyField0Div', 'manyField1Div']);
                        d.joinType = 'none';
                    }

                    set.joinType(d.joinType);
                    set.type(d.type);
                    switch (d.type) {
                        case 'kv':
                            $gs(['kvDiv']);
                            $g('kv').val(d.kv || '');
                            break;
                        case 'dict':
                            $gs(['dictIdDiv']);
                            $g('dictId').val(d.dictId || '');
                            break;
                        case 'tree':
                            $gs(['treesDiv']);
                            let o = $g('treeId');
                            try {
                                o.val(d.treeId || '');
                            } catch (e) {
                                o.val('');
                            }
                            o = $g('treeDisplay');
                            try {
                                o.val(d.treeDisplay = d.treeDisplay || 'separator');
                            } catch (e) {
                                o.val('');
                            }
                            break;
                        case 'tpl':
                            $gs(['tplDiv']);
                            $g('tpl').val(d.tpl || '')
                                .attr('placeholder', '支持ftl语法，例：\r\n\r\n<#if vo.state=1>\r\n ${vo.auser} 审核于：\r\n ${vo.atime?datetime}\r\n<#else>\r\n 未审核\r\n</#if>');
                    }
                    layui.form.render(null, rtForm.get('id'));
                },
                btns: function (btn) {
                    rtForm.find('.ls-tpl_' + args.uid).hide();
                    $gs(['ls_btns'], ['nulPropDiv']);
                    $g('btn_text').val(btn.text || '');
                    $g('btn_icon').val(btn.icon || (btn.icon = ''));
                    let sa = [], ae = btn.act === 'add' || btn.act === 'edit', act = btn.act, i;
                    fillOpts($g('btn_act'), false, btnTypes, btn.act);
                    btn.act = $g('btn_act').val();

                    $(rtForm).find('.btnpls').hide();/*先把不同类型的都隐藏*/
                    if (act === 'add' || act === 'edit' || act === 'page') {
                        $gs(['btn_pageIdDiv', 'btn_targetDiv', 'btn_titleDiv']);
                        let wrapOne = (it) => '<option value="' + it.id + '"' + (it.id === btn.goPageId ? ' selected' : '') + '>' + it.name + '</option>';
                        if (ae) {
                            sa = [];
                            for (i = 0; i < args.pageList.length; i++) {
                                if (args.pageList[i].type !== 'form' || !args.pageList[i].isMainTable) continue;
                                sa.push(wrapOne(args.pageList[i]));
                            }
                        } else {
                            sa = ['<option value="">=请选择=</option>'];
                            let inArr = [], lsArr = [], trArr = [],viArr=[];
                            for (i = 0; i < args.pageList.length; i++) {
                                let opt = wrapOne(args.pageList[i]), tpl = args.pageList[i].type;
                                if (tpl === 'form') inArr.push(opt);
                                else if (tpl === 'list') lsArr.push(opt);
                                else if (tpl === 'tree') trArr.push(opt);
                                else if (tpl === 'view') viArr.push(opt);
                            }
                            if (inArr.length) sa.push('<optgroup label="表单界面">', inArr.join('\n'), '</optgroup>');
                            if (viArr.length) sa.push('<optgroup label="详情界面">', viArr.join('\n'), '</optgroup>');
                            if (lsArr.length) sa.push('<optgroup label="列表界面">', lsArr.join('\n'), '</optgroup>');
                            if (trArr.length) sa.push('<optgroup label="树形界面">', trArr.join('\n'), '</optgroup>');
                        }
                        btn.goPageId = $g('btn_pageId').html(sa.join('')).val();

                        if (act === 'page') {
                            $gs(['btn_pageParamDiv']);
                            $g('btn_pageParam').val(btn.pageParam || '').attr('placeholder', '例：userId=${vo.id}');
                        }

                        btn.target = fillOpts($g('btn_target'), false, [['dialog', '弹出对话框'], ['tab', '新Tab标签']], btn.target).val();
                        $g('btn_title').val(btn.title || '').attr('placeholder', '例：${vo.name}资料修改');
                    } else if (act === 'link') {
                        $gs(['btn_outLinkDiv', 'btn_targetDiv']);
                        $g('btn_outLink').val(btn.outLink || '').attr('placeholder', '例：${ctx}/xx?id=${vo.id}');
                        btn.target = fillOpts($g('btn_target'), false, [['dialog', '弹出对话框'], ['tab', '新Tab标签'], ['_blank', '浏览器新页面']], btn.target).val();

                        if (btn.target !== '_blank') {
                            $gs(['btn_titleDiv']);
                            $g('btn_title').val(btn.title || '').attr('placeholder', '例：${vo.name}资料修改');
                        }
                    }
                    if (btn.act === 'update') {
                        $gs(['btn_updateCodeDiv']);
                        $g('btn_updateCode').val(btn.updateCode || '');
                    }
                    if (btn.act === 'del' || btn.act === 'update' || btn.act === 'exec' || btn.act === 'ajax') {
                        $gs(['btn_confirmDiv']);
                        $g('btn_confirm').val(btn.confirm || '');
                        if (btn.act === 'ajax') {
                            $gs(['btn_ajaxUrlDiv']);
                            $g('btn_ajaxUrl').val(btn.ajaxUrl || '');
                        }
                    }
                    if (btn.target === 'dialog'
                        && (btn.act === 'add' || btn.act === 'edit' || btn.act === 'page' || btn.act === 'link')) {
                        $gs(['btn_widthDiv', 'btn_heightDiv']);
                        $g('btn_width').val(btn.width || (btn.width = 640));
                        $g('btn_height').val(btn.height || (btn.height = 480));
                    }
                    $gs(['btn_grantCodeDiv', 'btn_conditionShowDiv']);
                    $g('btn_grantCode').val(btn.grantCode || '');
                    $g('btn_conditionShow').val(btn.conditionShow || '');
                    layui.colorpicker.render({
                        elem: '#btn_fg_' + args.uid
                        , color: btn.fg || ''
                        , predefine: true
                        , done: function (color) {
                            btn.fg = color;
                            let t = canvas.find('.jdiy-selected');
                            t.find('button').css({color: color});
                        }
                    });
                    layui.colorpicker.render({
                        elem: '#btn_bg_' + args.uid
                        , color: btn.bg || ''
                        , predefine: true
                        , done: function (color) {
                            btn.bg = color;
                            let t = canvas.find('.jdiy-selected');
                            t.find('button').css({backgroundColor: color});
                        }
                    });

                    footerBtnShow(btn)
                    layui.form.render(null, rtForm.attr('id'));
                },
                tabs: function (d) {
                    rtForm.find('.ls-tpl_' + args.uid).hide();
                    $gs(['ls_tabs'], ['nulPropDiv']);
                    $g('tab_label').val(d.label || '');
                    if (d.type === 2) {
                        $gs(['tab_goUrlDiv'], ['tab_goPageIdDiv', 'tab_goPageParamDiv', 'tab_goPageFilterDiv']);
                        $g('tab_goUrl').val(d.goUrl || '');
                    } else {
                        d.type = 1;
                        $gs(['tab_goPageIdDiv', 'tab_goPageParamDiv', 'tab_goPageFilterDiv'], ['tab_goUrlDiv']);

                        let wrapOne = (it) => '<option value="' + it.id + '"' + (it.id === d.goPageId ? ' selected' : '') + '>' + it.name + '</option>';

                        let sa = ['<option value="">=请选择=</option>'];
                        let inArr = [], lsArr = [], trArr = [],viArr=[];
                        for (let i = 0; i < args.pageList.length; i++) {
                            let opt = wrapOne(args.pageList[i]), tpl = args.pageList[i].type;
                            if (tpl === 'form') inArr.push(opt);
                            else if (tpl === 'list') lsArr.push(opt);
                            else if (tpl === 'tree') trArr.push(opt);
                            else if (tpl === 'view' && args.pageList[i].id!==args.uid) viArr.push(opt);
                        }
                        if (lsArr.length) sa.push('<optgroup label="列表界面">', lsArr.join('\n'), '</optgroup>');
                        if (trArr.length) sa.push('<optgroup label="树形界面">', trArr.join('\n'), '</optgroup>');
                        if (viArr.length) sa.push('<optgroup label="详情界面">', viArr.join('\n'), '</optgroup>');
                        if (inArr.length) sa.push('<optgroup label="表单界面">', inArr.join('\n'), '</optgroup>');

                        d.goPageId = $g('tab_goPageId').html(sa.join('')).val();
                        $g('tab_goPageParam').val(d.goPageParam || '').attr('placeholder', '例：xx_id=${vo.id}');
                        $g('tab_goPageFilter').val(d.goPageFilter || '').attr('placeholder', '例：o.xx_id=\'${vo.id}\'');
                    }
                    $g('tab_type').val(d.type);
                    layui.form.render(null, rtForm.attr('id'));
                }
            },
            reset = function (data, selectedId) {
                let _done = function () {
                    sData = data;
                    $g('tabPos').val(data.tabPos = data.tabPos || 0);
                    $g('tabTitle').val(data.tabTitle = data.tabTitle || '');
                    $g('vi_btn').prop('checked', sData.btn = !!sData.btn);
                    $g('sqlFilter').val(data.sqlFilter || '');
                    $g('pageHandler').val(data.pageHandler);
                    builder.btns(sData.btns);
                    builder.tds();
                    builder.tabs();

                    $g('headTips').val(data.headTips || '');
                    if (data.headTips != null && data.headTips !== '') {
                        $g('headTipsBlock').html(data.headTips).show();
                    }
                    $g('footTips').val(data.footTips || '');
                    if (data.footTips != null && data.footTips !== '') {
                        $g('footTipsBlock').html(data.footTips).show();
                    }
                    if (selectedId) doSelect(selectedId);
                    layui.form.render(null, canvas.attr('id'));
                    layui.form.render(null, rtForm.attr('id'));
                };
                if (data) {
                    _done();
                } else {
                    jdiyAdmin.ajax({
                        url: jdiyAdmin.ctx + '/mgmt/JDiyAdmin/ui.meta?pageId=' + args.uid,
                        type: 'post',
                        success: function (ret) {
                            if (ret.code !== 200) {
                                jdiyAdmin.error(ret.msg);
                                return;
                            }
                            reset(ret.data, selectedId);
                        }
                    });
                }
            },
            save = function () {
                let selectedId;
                try {
                    selectedId = canvas.find('.jdiy-selected').attr('id');
                } catch (e) {
                    selectedId = null;
                }
                formatTds();
                if (sData.tds.length === 0) {
                    jdiyAdmin.error('您还没有添加配置任何表单控件！');
                    return;
                }
                jdiyAdmin.ajax({
                    url: jdiyAdmin.ctx + '/mgmt/JDiyAdmin/view.saveDesign.' + args.uid,
                    data: {
                        s: JSON.stringify(sData)
                    },
                    type: 'post',
                    success: function (ret) {
                        if (ret.code !== 200) {
                            if (ret.code === 203 && ret.inputId) doSelect(ret.inputId);
                            jdiyAdmin.error(ret.msg);
                            return;
                        }
                        reset(null, selectedId);
                        layui.layer.msg(ret.msg);
                    }
                });
            },
            addNew = function (t) {
                let id = jdiyAdmin.util.newId(),
                    oid = t && t.attr ? t.attr('id').substring(10) : null,
                    aa = function (arr, d) {
                        let is = false, i;
                        for (i = arr.length; i--;) {
                            if (arr[i].id === oid && i < arr.length - 1) {
                                arr.splice(i + 1, 0, d);
                                is = true;
                                break;
                            }
                        }
                        if (!is) arr.push(d);
                    };
                if (t === 'firstTd') {
                    let nd = {
                        id: id,
                        type: 'direct',
                        label: '标题文字' + addNewId++,
                        joinType: 'none'
                    };
                    sData.btns = [nd];
                    let n = $('<div class="layui-form-item">' + builder.wrap(eData[id] = nd) + '</div>').appendTo(divTds);
                    doSelect(n.children(':first'));
                    return;
                }
                if (!t.length) return;
                if (t.hasClass('vibtn')) {
                    let d = sBtns[id] = {
                        id: id,
                        text: '新操作按钮' + addNewId++,
                        act: 'edit'
                    };
                    aa(sData.btns, d);
                    $(builder.btn(d)).insertAfter(t);
                    doSelect('jdiyviobj_' + id);
                } else if (t.hasClass('vitxt')) {
                    let nd = {
                        id: id,
                        type: 'direct',
                        label: '标题文字' + addNewId++,
                        joinType: 'none'
                    };
                    aa(sData.tds, nd);
                    let p = t.parents('.layui-form-item');
                    if (p.find('.vitxt').length >= 2) {
                        let n = $('<div class="layui-form-item">' + builder.wrap(eData[id] = nd) + '</div>').insertAfter(p);
                        doSelect(n.children(':first'));
                    } else {
                        let n = $(builder.wrap(eData[id] = nd)).insertAfter(t);
                        doSelect(n);
                    }
                } else if (t.hasClass('vitab')) {
                    let d = sTabs[id] = {
                        id: id,
                        label: '新Tab' + addNewId++
                    };
                    aa(sData.tabs, d);
                    builder.tabs();
                    doSelect('jdiyviobj_' + id);
                } else if (t.hasClass('vitabThis')) {
                    let d = sTabs[id] = {
                        id: id,
                        label: '新Tab' + addNewId++
                    };
                    sData.tabs.splice(0, 0, d);
                    builder.tabs();
                    doSelect('jdiyviobj_' + id);
                }
            },
            remove = function (t) {
                let id = t.attr('id').substring(10), n, l, i, p = 'jdiyviobj_',
                    update = (a) => {
                        for (i = a.length; i--;) {
                            if (a[i].id === id) {
                                if (i < a.length - 1) n = a[i + 1];
                                else if (i > 0) n = a[i - 1];
                                else n = null;
                                a.splice(i, 1);
                                break;
                            }
                        }
                        return a;
                    };
                if (t.hasClass('vitxt')) {
                    if (sData.tds.length < 2) {
                        layui.layer.msg('至少需要保留一个字段显示,再删就没有了！');
                        return;
                    }
                    builder.tds(update(sData.tds));
                } else if (t.hasClass('vibtn')) {
                    if (sData.btns.length < 2) {
                        layui.element.tabChange('rtTab_' + args.uid, 'rtTab1_' + args.uid);
                        $g('vi_btn').prop('checked', sData.btn = false);
                        layui.form.render(null, rtForm.attr('id'));
                        layui.layer.tips('详情页控制按钮已关闭，可从此处重新开启！', '.jdev-prop-vi_btn' + args.uid, {
                            tips: [4, '#db5621'],
                            time: 10000
                        });
                        builder.btns(sData.btns);
                        return;
                    }
                    if (update(sData.btns).length > 0) t.remove();
                } else if (t.hasClass('vitab')) {
                    if (sData.tabPos === 2 && sData.tabs.length === 1) {
                        $g('tabPos').val(sData.tabPos = 0);/*tab位于页面下方，最后一个删除即表示不显示子表tab*/
                        builder.tabs();

                        layui.form.render('select', rtForm.attr('id'));
                        layui.element.tabChange('rtTab_' + args.uid, 'rtTab1_' + args.uid);
                        layui.layer.tips('Tab功能已关闭，可从此处重新开启！', '.jdev-prop-tabPos' + args.uid, {
                            tips: [4, '#db5621'],
                            time: 10000
                        });
                        return;
                    }
                    if (update(sData.tabs).length < 1) builder.tabs();
                    else t.remove();
                    if (sData.tabs.length < 1) doSelect('vitabThis_' + args.uid);
                } else if (t.hasClass('vitabThis')) {
                    if (sData.tabs.length === 0) {
                        $g('tabPos').val(sData.tabPos = 0);
                        builder.tabs();
                        layui.form.render('select', rtForm.attr('id'));
                        layui.element.tabChange('rtTab_' + args.uid, 'rtTab1_' + args.uid);
                        layui.layer.tips('Tab功能已关闭，可从此处重新开启！', '.jdev-prop-tabPos' + args.uid, {
                            tips: [4, '#db5621'],
                            time: 10000
                        });
                    } else
                        layui.layer.tips('第1个是主表Tab，后面还有其它Tab时，我不可移除', '#vitabThis_' + args.uid, {
                            tips: [4, '#db5621'],
                            time: 10000
                        });
                    return;
                }
                if (n) doSelect('jdiyviobj_' + n.id);
                else propRender.nul();
            },
            toolHtml = '<div class="layui-btn-group jdiy-design-tool">\n' +
                '        <button type="button" class="layui-btn layui-btn-xs layui-bg-black add-tool" title="在它后面增加"><i class="layui-icon layui-icon-add-1"></i></button>\n' +
                '        <button type="button" class="layui-btn layui-btn-xs layui-bg-black del-tool" title="移除选中项"><i class="layui-icon layui-icon-delete"></i></button>\n' +
                '    </div>',
            showTool = function (t) {
                canvas.find('.jdiy-design-tool').remove();
                if (t && t.length) {
                    let tool = t.is('.vibtn')
                        ? $(toolHtml).insertBefore(t).css({
                            marginLeft: 0,
                            marginTop: '30px'
                        })
                        : $(toolHtml).prependTo(t).css({
                            marginLeft: 0,
                            marginTop: (t.outerHeight()) + 'px'
                        });
                    tool.find('.add-tool').click(function () {
                        let t = canvas.find('.jdiy-selected');
                        addNew(t);
                    });
                    tool.find('.del-tool').click(function () {
                        let t = canvas.find('.jdiy-selected');
                        showTool();
                        remove(t);/*
                        let t = canvas.find('.jdiy-selected'),
                            i = t.attr('id').substring(10),
                            l = eData[i].label,
                            p = t.parent(), n;
                        t.remove();
                        p.find('.jdiy-design-tool').remove();
                        if (p.children().length < 1) {
                            n = p.next().find('.jdiy-vi-obj:first');
                            p.remove();
                        } else {
                            n = p.find('.jdiy-vi-obj:first');
                        }
                        if (n.length !== 1) n = canvas.find('.jdiy-vi-obj:last');
                        if (n.length === 1) doSelect(n);
                        else builder.empty();
                        delete eData[i];*/
                    });

                }
            },
            doSelect = function (target) {
                let oThis = typeof target == 'string' ? $('#' + target) : target, o = oThis;
                if (oThis.is('.jdiy-vi-obj.vitxt')) {
                    if (!$g('rtTab0').hasClass('layui-this')) layui.element.tabChange('rtTab_' + args.uid, 'rtTab0_' + args.uid);
                    canvas.find('.jdiy-selected').removeClass('jdiy-selected');
                    o.addClass('jdiy-selected');
                    canvas.find('.jdiy-in-thisRow').removeClass('jdiy-in-thisRow');
                    o.parents('.layui-form-item').addClass('jdiy-in-thisRow');
                    let d = eData[o.attr('id').substring(10)];
                    setTimeout(function () {
                        propRender.tds(d);
                    }, 100);/*一定要加个定时器防止上一个控件属性还没有来得及保存*/
                } else if ((o = oThis).is('.jdiy-vi-obj.vibtn') || (o = oThis.parents('.jdiy-vi-obj.vibtn')).length === 1) {
                    layui.element.tabChange('rtTab_' + args.uid, 'rtTab0_' + args.uid);
                    canvas.find('.jdiy-vi-obj.jdiy-selected').removeClass('jdiy-selected');
                    o.addClass('jdiy-selected');
                    propRender.btns(sBtns[o.attr('id').substring(10)]);
                } else if ((o = oThis).is('.jdiy-vi-obj.vitab') || (o = oThis.parents('.jdiy-vi-obj.vitab')).length === 1) {
                    layui.element.tabChange('rtTab_' + args.uid, 'rtTab0_' + args.uid);
                    canvas.find('.jdiy-vi-obj.jdiy-selected').removeClass('jdiy-selected');
                    o.addClass('jdiy-selected');
                    propRender.tabs(sTabs[o.attr('id').substring(10)]);
                } else if ((o = oThis).is('.jdiy-vi-obj.vitabThis') || (o = oThis.parents('.jdiy-vi-obj.vitabThis')).length === 1) {
                    propRender.nul();
                    layui.element.tabChange('rtTab_' + args.uid, 'rtTab1_' + args.uid);
                    canvas.find('.jdiy-vi-obj.jdiy-selected').removeClass('jdiy-selected');
                    o.addClass('jdiy-selected');
                    $g('tabTitle').focus();
                } else {
                    propRender.nul();
                }
                showTool(o);
            },
            builder = {
                empty: function () {
                    let aid = jdiyAdmin.util.newId();
                    divTds.html('<div style="padding:50px;text-align: center;border:1px #c00 dotted;">\n' +
                        '<div style="margin-bottom: 20px;font-size:16px;color:red;">空空如也，请点击下面按钮添加显示内容。</div>\n' +
                        '<button type="button" id="' + aid + '" class="layui-btn layui-btn-sm addFirst layui-btn-danger"><i class="layui-icon layui-icon-add-1"></i>添加控件</button>\n' +
                        '</div>');
                    $('#' + aid).click(function () {
                        divTds.html('');
                        addNew('firstTd');
                    });

                    propRender.nul();
                },
                tds: function () {
                    let sa = [], lastRow = -1, selectedId = null, t = divTds.find('.jdiy-selected');
                    if (t && t.length) selectedId = t.attr('id');

                    if (sData.tds && sData.tds.length) {
                        for (let i = 0; i < sData.tds.length; i++) {
                            let d = sData.tds[i];
                            if (lastRow === -1 || lastRow !== d.row) {
                                if (lastRow !== -1) sa.push('</div>')
                                sa.push('<div class="layui-form-item">');
                                lastRow = d.row;
                            }
                            eData[d.id] = d;
                            sa.push(builder.wrap(d));
                            if (i === sData.tds.length - 1) sa.push('</div>');
                        }
                    }
                    if (sa.length) {
                        divTds.html(sa.join('\n'));
                        if (t && t.length) {
                            t.attr('id').substring(10);
                            doSelect(selectedId);
                        } else propRender.nul();
                    } else {
                        builder.empty();
                    }
                },
                row: function (canvas, rowArray) {
                    let sa = [], i, d;
                    for (i = 0; i < rowArray.length; i++) {
                        d = rowArray[i];
                        eData[d.id] = d;
                        sa.push(builder.wrap(d));
                    }
                    return sa.join('\n');
                },
                wrap: function (d) {
                    let layCss = 'layui-col-xs6', labelCss = 'layui-form-label', sa = [];
                    sa.push('<div class="' + layCss + ' jdiy-vi-obj vitxt" id="jdiyviobj_' + d.id + '">');
                    sa.push('<label class="' + labelCss + '">' + d.label + '</label>');
                    sa.push(builder.item.call(d));
                    sa.push('</div>');
                    return sa.join('\n');
                },
                item: function () {
                    let val = this.field ? '${vo.' + this.field + '}' : '';
                    if (this.type === 'kv') val += '<span style="color:#01AAED"> (K/V互转)</span>';
                    else if (this.type === 'dict') val += '<span style="color:#01AAED"> (字典:' + (this.dictId || '') + ')</span>';
                    else if (this.type === 'tree') val += '<span style="color:#01AAED"> (树层级)</span>';
                    else if (this.type === 'tpl') val = '<span style="color:#6f01ed"> &lt;模板输出&gt;</span>';
                    else if (this.type === 'img') val += '<span style="color:#01AAED">(缩略图)</span>';
                    else if (this.type === 'file') val += '<span style="color:#01AAED">(附件链接)</span>';

                    return '<div class="layui-input-block inpDiv"><div class="layui-form-mid">' + val + '</div></div>';
                },
                btns: function (btns) {
                    if (!btns || btns.length < 1 || !sData.btn) {
                        divBtn0.hide();
                        return;
                    }
                    let sa = [], i;
                    for (i = 0; i < btns.length; i++) sa.push(builder.btn(sBtns[btns[i].id] = btns[i]));
                    divBtn0.show().html(sa.join(''));
                },
                btn: (btn) => {
                    let text = btn.text || '',
                        icon = btn.icon
                            ? '<i class="layui-icon ' + btn.icon + '"></i>'
                            : '';
                    return '<div class="layui-inline jdiy-vi-obj vibtn" id="jdiyviobj_' + btn.id
                        + '"><button style="' +
                        (btn.bg && btn.bg !== '' ? 'background-color:' + btn.bg + ';' : '') +
                        (btn.fg && btn.fg !== '' ? 'color:' + btn.fg + ';' : '') +
                        '" class="layui-btn layui-btn-sm" type="button">' + icon + text + '</button></div>'
                },
                tabs: function () {
                    let topTab = $('#topTab_' + args.uid).empty(),
                        underTab = $('#underTab_' + args.uid).empty(),
                        newTabArr = [{label: '子表tab1', id: jdiyAdmin.util.newId()}, {
                            label: '点击Tab选中',
                            id: jdiyAdmin.util.newId() + 1
                        }, {
                            label: '再次按下拖拽排序',
                            id: jdiyAdmin.util.newId() + 2
                        }];
                    if (sData.tabPos === 1) {
                        $gs(['tabTitleDiv']);
                        let tabs = $('<ul class="layui-tab-title" style="margin-bottom: 20px;"></ul>')
                            .appendTo(topTab);
                        $('<li class="layui-this vitabThis jdiy-vi-obj" id="vitabThis_' + args.uid + '"><span>' + (sData.tabTitle || '基本信息') + '</span></li>').appendTo(tabs);
                        if (!sData.tabs) sData.tabs = newTabArr;
                        for (let i = 0; i < sData.tabs.length; i++) builder.tab(sTabs[sData.tabs[i].id] = sData.tabs[i]).appendTo(tabs);

                    } else if (sData.tabPos === 2) {
                        $gs(['tabTitleDiv']);
                        topTab.html(!sData.tabTitle ? '' : '<div id="vitabThis_' + args.uid + '"><span>' + sData.tabTitle + '</span>：</div>');
                        let tabs = $('<ul class="layui-tab-title" style="margin-top: 20px;"></ul>')
                            .appendTo(underTab);
                        if (!sData.tabs || sData.tabs.length < 1) sData.tabs = newTabArr;
                        for (let i = 0; i < sData.tabs.length; i++) builder.tab(sTabs[sData.tabs[i].id] = sData.tabs[i], i === 0).appendTo(tabs);
                        $('<div style="height:150px;"></div>').appendTo(underTab);
                    }else{
                        $gs([],['tabTitleDiv']);
                    }
                },
                tab: function (d, tabThis) {
                    return $('<li id="jdiyviobj_' + d.id + '" class="vitab jdiy-vi-obj' + (tabThis ? ' layui-this' : '') + '"><span>' + (d.label||'Tab标题') + '</span></li>');
                },
                propSet: {
                    field: function (val) {
                        $gs(['fieldsDiv']);
                        let o = $g('field');
                        if (val === undefined || val === null) val = '';
                        loadFields(args.bindType === 'entity', args.bindType === 'table' ? args.mainTable : args.mainEntity, function (r) {
                            fillOpts($g('field'), '请选择', r.data, val, (it) => [
                                it[0], it[0] + '　- ' + it[1]
                            ]);
                            $g('field').append('<option value="@">其它自定义</option>');

                            if (!val || o.find('option[value=' + val + ']').length) {
                                $gs([], ['tFieldDiv']);
                            } else {
                                o.val('@');
                                $gs(['tFieldDiv']);
                                $g('tField').val(val);
                            }
                            layui.form.render(null, rtForm.attr('id'));
                        });
                    },
                    joinType: function (val) {
                        $gs(['joinTypeDiv']);
                        let o = $g('joinType');
                        try {
                            o.val(val || 'none');
                        } catch (e) {
                            o.val('none');
                        }
                    },
                    treeId: function (val, d) {
                        $gs(['treeIdDiv', 'treeDisplayDiv']);
                        let o = $g('treeId');
                        try {
                            o.val(val || '');
                        } catch (e) {
                            o.val('');
                        }
                        o = $g('treeDisplay');
                        try {
                            o.val(d.treeDisplay || 'separator');
                        } catch (e) {
                            o.val('');
                        }
                        d.treeDisplay = o.val();

                    },
                    label: function (val) {
                        $gs(['labelDiv']);
                        $g('label').val(val);
                    },
                    type: function (val) {
                        $gs(['typeDiv']);
                        let o = $g('type');
                        try {
                            o.val(val || 'direct');
                        } catch (e) {
                            o.val('direct');
                        }
                    }
                }
            };

        if (!body.data('inDrag_isBind')) {
            jdiyAdmin.inDesign = {
                dragging: false,
                dragThis: null,
                dragThat: null,
                dragTo: null,
                mouse: null,
                pos: 0, /*上右下左: 1234*/
                line: $('<div class="jdiy-drag-line"></div>').appendTo(body),
                follow: $('<div class="jdiy-drag-follow">拖拽鼠标可调整选中元素位置</div>').appendTo(body)
            };
            body.data('inDrag_isBind', true);
            body.mousemove(function (evt) {
                let drag = jdiyAdmin.inDesign;
                if (drag.dragging) {
                    drag.follow.css({
                        left: (evt.clientX + 30) + 'px',
                        top: (evt.clientY + 20) + 'px'
                    }).show();
                }
            }).mouseup(function () {
                $('body').removeClass('drag-move');
                $('.jdiy-drag-highlight').removeClass('jdiy-drag-highlight');
                let drag = jdiyAdmin.inDesign || {};
                if (!drag.dragging) return;

                drag.follow.hide();
                drag.line.hide();
                drag.dragTo = null;
                drag.dragging = false;
            });
        }
        canvas.mouseup(function (e) {
            setTimeout(function () {
                let oThis = canvas.find('.jdiy-selected');
                showTool(oThis);
            }, 200);

            let drag = jdiyAdmin.inDesign || {};
            if (drag.dragThis) setOpacity(drag.dragThis, 1);
            if (drag.dragging && drag.dragTo) {
                let i, pos, it,
                    fid = drag.dragThis.attr('id').substring(10),
                    tid = drag.dragTo.attr('id').substring(10),
                    mva = function (a, d) {
                        for (i = a.length; i--;) {
                            pos = drag.pos === 1 ? i : i + 1;
                            if ((it = a[i]).id === fid) a.splice(i, 1);
                            else if (it.id === tid) a.splice(pos, 0, d[fid]);
                        }
                        return a;
                    },
                    mv = function () {
                        if (drag.pos === 1) drag.dragThis.insertBefore(drag.dragTo);
                        else drag.dragThis.insertAfter(drag.dragTo);
                    };

                if (drag.pos && drag.line.is(':visible') && fid !== tid) {
                    if (drag.dragThis.hasClass('vitxt')) {
                        let p, np, toJq;
                        if (drag.pos === 1 || drag.pos === 3) {//1:目标元素上方  3:置于目标元素下方
                            toJq = drag.dragTo.hasClass('layui-form-item') ? drag.dragTo : drag.dragTo.parent();
                            p = drag.dragThis.parent();
                            if (drag.pos === 1) np = $('<div class="layui-form-item"></div>').insertBefore(toJq);
                            else np = $('<div class="layui-form-item"></div>').insertAfter(toJq);
                            drag.dragThis = drag.dragThis.css({opacity: 1}).appendTo(np);
                            if (p.children().length < 1) p.remove();
                        } else if (drag.pos === 2 || drag.pos === 4) {//2:目标元素右方  4:目标元素左左方
                            p = drag.dragThis.parent();
                            if (drag.pos === 4) drag.dragThis.insertBefore(drag.dragTo);
                            else drag.dragThis.insertAfter(drag.dragTo);
                            if (p.children().length < 1) p.remove();
                        }
                        formatTds();
                        builder.tds();
                    } else if (drag.dragThis.hasClass('vibtn')) {
                        mva(sData.btns, sBtns);
                        mv();
                    } else if (drag.dragThis.hasClass('vitab')) {
                        mva(sData.tabs, sTabs);
                        mv();
                    }
                }
            }
        }).mousedown(function (e) {
            let dragThis = $(e.target),
                selected = canvas.find('.jdiy-selected'),
                isTool = dragThis.hasClass('jdiy-design-tool') || dragThis.parents('.jdiy-design-tool').length > 0;
            if (isTool) return;
            if (!dragThis.hasClass('jdiy-vi-obj')) dragThis = dragThis.parents('.jdiy-vi-obj');
            if (dragThis.is(selected)) {
                if (!dragThis.hasClass('vitabThis')) {
                    body.addClass('drag-move');
                    startDrag(e, dragThis);
                } else {
                    layui.layer.tips('主表Tab不可移动位置', '#vitabThis_' + args.uid, {
                        tips: [4, '#db5621'],
                        time: 10000
                    });
                }
                showTool();
            } else if (dragThis.length === 1) {
                doSelect(dragThis);
            }
        }).mousemove(function (e) {
            let drag = jdiyAdmin.inDesign || {};
            if (!drag.dragging) return;
            let t = $(e.target), c1 = null;
            if (!t.hasClass('jdiy-vi-obj')) t = t.parents('.jdiy-vi-obj');
            if (t.length < 1) return;
            if (drag.dragThis.hasClass('vitxt')) c1 = 'vitxt';
            else if (drag.dragThis.hasClass('vibtn')) c1 = 'vibtn';
            else if (drag.dragThis.hasClass('vitab')) c1 = 'vitab';

            if (c1 === null || !t.hasClass(c1)) return;


            let that = drag.dragThat = t;

            if (drag.dragThat.is(drag.dragThis)) {
                drag.line.hide();
                drag.dragTo = null;
                drag.follow.html('拖拽鼠标可调整选中元素位置').css('color', 'red').show();
                canvas.find('.jdiy-drag-highlight').removeClass('jdiy-drag-highlight');
            } else {
                if (c1 === 'vitxt') {/*详情表格可以上下移动，因此直接拿form的拖拽代码来单独处理*/
                    let ofX = e.clientX - drag.mouse.x, ofXa = Math.abs(ofX),
                        ofY = e.clientY - drag.mouse.y, ofYa = Math.abs(ofY),
                        lazy = 5,//移过指定像素，才判断显示目标位置
                        toob,
                        css1;
                    if (ofYa < ofXa) {
                        toob = that;
                        css1 = {width: '3px', height: that.outerHeight() + 'px', top: (that.offset().top) + 'px'};
                        if (ofX > lazy) {//右
                            drag.pos = 2;
                            css1.left = (toob.offset().left + 6 + toob.outerWidth()) + 'px';
                        } else if (ofX < -lazy) {//左
                            drag.pos = 4;
                            css1.left = (toob.offset().left - 6) + 'px';
                        } else {
                            css1 = null;
                        }
                    } else {
                        toob = that.hasClass('layui-inline') ? that.parent() : that;
                        css1 = {height: '3px', width: toob.outerWidth() + 'px', left: (toob.offset().left) + 'px'};
                        if (ofY > lazy) {//下
                            drag.pos = 3;
                            css1.top = (toob.offset().top + 6 + toob.outerHeight()) + 'px';
                        } else if (ofY < -lazy) {//上
                            drag.pos = 1;
                            css1.top = (toob.offset().top - 6) + 'px';
                        } else {
                            css1 = null;
                        }
                    }
                    if (css1 != null) {
                        canvas.find('.jdiy-drag-highlight').removeClass('jdiy-drag-highlight');
                        toob.addClass('jdiy-drag-highlight');
                        drag.mouse = {x: e.clientX, y: e.clientY};
                        drag.dragTo = that;
                        drag.line.show().css(css1);
                        drag.dragThis.css({opacity: 0.1});
                        drag.follow.show().html('放开鼠标可将元素移至红线处').css('color', 'green');
                    }
                } else {
                    let ofX = e.clientX - drag.mouse.x,
                        lazy = 5,//移过指定像素，才判断显示目标位置
                        toob = that,
                        css1 = getLineCss(that);//todo
                    if (ofX > lazy) {//右
                        drag.pos = 2;
                        css1.left = (toob.offset().left + toob.outerWidth()) + 'px';
                    } else if (ofX < -lazy) {//左
                        drag.pos = 1;
                        css1.left = (toob.offset().left) + 'px';
                    } else {
                        css1 = null;
                    }
                    setOpacity(drag.dragThis, 0.1);
                    if (css1 != null) {
                        canvas.find('.jdiy-drag-highlight').removeClass('jdiy-drag-highlight');
                        if (c1 !== 'col') toob.addClass('jdiy-drag-highlight');
                        drag.mouse = {x: e.clientX, y: e.clientY};
                        drag.dragTo = that;
                        drag.line.show().css(css1);
                        drag.follow.show().html('放开鼠标可将元素移至红线处').css('color', 'green');
                    }
                }
            }
        });

        selectOn('type', function (o) {
            let {t, d} = $selected(), nt;
            d.type = o.value;
            let h = builder.wrap(d);
            nt = $(h).insertAfter(t).addClass('jdiy-selected');
            t.remove();
            layui.form.render(null, canvas.attr('id'));

            propRender.tds(d);
            doSelect(nt);
        });

        selectOn('field', function (o) {
            let {t, d} = $selected();
            if (o.value === '@') {
                $gs(['tFieldDiv']);
                $g('tField').val(d.field = '');
            } else {
                $gs([], ['tFieldDiv']);
                d.field = o.value;
            }
            $(builder.wrap(d)).insertAfter(t).addClass('jdiy-selected');
            t.remove();
            layui.form.render(null, canvas.attr('id'));
        });

        selectOn('joinType', function (o) {
            let {d} = $selected();
            d.joinType = o.value;
            propRender.tds(d);
        });
        selectOn('joinTable', joinTableOn);
        selectOn('joinField', function (o) {
            let {d} = $selected();
            d.joinField = o.value;
        });
        selectOn('joinRef', function (o) {
            let {d} = $selected();
            d.joinRef = o.value;
        });
        selectOn('manyTable', manyTableOn);
        selectOn('manyField0', function (o) {
            let {d} = $selected();
            d.manyField0 = o.value;
        });
        selectOn('manyField1', function (o) {
            let {d} = $selected();
            d.manyField1 = o.value;
        });


        selectOn('treeId', function (o) {
            let {d} = $selected();
            d.treeId = o.value;
        });
        selectOn('treeDisplay', function (o) {
            let {d} = $selected();
            d.treeDisplay = o.value;
        });
        selectOn('manyType', function (o) {
            let {d} = $selected();
            d.manyType = o.value;
            propRender.tds(d);
        });
        selectOn('manyField0', function (o) {
            let {d} = $selected();
            d.manyField0 = o.value;
        });
        selectOn('manyField1', function (o) {
            let {d} = $selected();
            d.manyField1 = o.value;
        });
        $g('tField').keyup(function () {
            let {t, d} = $selected();
            if (this.value !== '' && !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(this.value)) {
                let ov = $(this).data('oldval');
                this.value = ov === undefined || ov == null ? '' : ov;
            } else {
                $(this).data('oldval', this.value);
            }
            d.field = this.value;
            $(builder.wrap(d)).insertAfter(t).addClass('jdiy-selected');
            t.remove();
            layui.form.render(null, canvas.attr('id'));
        });

        $g('label').keyup(function () {
            let {t, d} = $selected();
            d.label = this.value;
            t.find('>label').html(this.value);
        });
        $g('kv').keyup(function () {
            let {t, d} = $selected();
            d.kv = this.value;
        });
        $g('tpl').keyup(function () {
            let {t, d} = $selected();
            d.tpl = this.value;
        });
        selectOn('dictId', function (o) {
            let {t, d} = $selected();
            d.dictId = o.value;

            let h = builder.wrap(d), nt = $(h).insertAfter(t).addClass('jdiy-selected');
            t.remove();
            layui.form.render(null, canvas.attr('id'));
            doSelect(nt);
        });


        $g('btn_text').keyup(function () {
            let {t, pos, d} = $selBtn();
            d.text = this.value;
            $(builder.btn(d, pos)).insertBefore(t).addClass('jdiy-selected');
            t.remove();
        });

        $g('btn_icon').click(function () {
            layui.layer.open({
                type: 8,
                title: '选择图标',
                area: ['480px', '340px'],
                content: jdiyAdmin.ctx + '/mgmt/JDiyAdmin/ui.icon?fn=viChooseIcon_' + args.uid,
                btn: ['确定', '取消'],
                yes: function (index, layero) {
                    layero.find("button.submit").click();
                }
            });
            $(this).data('btnid', canvas.find('.jdiy-selected').attr('id'));
        }).change(function () {
            let id = $(this).data('btnid'),
                btnid = id.substring(10),
                t = $('#' + id),
                d = sBtns[btnid];
            d.icon = this.value;
            $(builder.btn(d)).insertBefore(t).addClass('jdiy-selected');
            t.remove();
        });
        selectOn('btn_act', function (o) {
            let {d} = $selBtn();
            d.act = o.value;
            propRender.btns(d);
        });

        $g('btn_updateCode').keyup(function () {
            let {d} = $selBtn();
            d.updateCode = this.value;
        });
        selectOn('btn_pageId', function (o) {
            let {d} = $selBtn();
            d.goPageId = o.value;
        });
        $g('btn_pageParam').keyup(function () {
            let {d} = $selBtn();
            d.pageParam = this.value;
        });
        $g('btn_outLink').keyup(function () {
            let {d} = $selBtn();
            d.outLink = this.value;
        });
        selectOn('btn_target', function (o) {
            let {d} = $selBtn();
            d.target = o.value;
            propRender.btns(d);
        });

        $g('btn_title').keyup(function () {
            let {d} = $selBtn();
            d.title = this.value;
        });

        $g('btn_width').keyup(function () {
            let {d} = $selBtn();
            d.width = this.value;
        });

        $g('btn_height').keyup(function () {
            let {d} = $selBtn();
            d.height = this.value;
        });

        $g('btn_confirm').keyup(function () {
            let {d} = $selBtn();
            d.confirm = this.value;
        });
        $g('btn_ajaxUrl').keyup(function () {
            let {d} = $selBtn();
            d.ajaxUrl = this.value;
        });
        $g('btn_grantCode').keyup(function () {
            let {d} = $selBtn();
            d.grantCode = this.value;
        });
        $g('btn_conditionShow').keyup(function () {
            let {d} = $selBtn();
            d.conditionShow = this.value;
        });
        switchOn('btn_footer', function (o) {
            let {d} = $selBtn();
            d.footer = o.elem.checked;
        });


        selectOn('tabPos', function (o) {
            sData.tabPos = parseInt(o.value);
            builder.tabs();
        });
        switchOn('vi_btn', function (o) {
            sData.btn = o.elem.checked;
            if (!sData.btns || sData.btns.length < 1) {
                sData.btns = [
                    {
                        id: jdiyAdmin.util.newId(),
                        text: '修改',
                        act: 'edit'
                    }, {
                        id: jdiyAdmin.util.newId() + 1,
                        text: '删除',
                        bg: '#ff5722',
                        act: 'del'
                    }, {
                        id: jdiyAdmin.util.newId() + 2,
                        text: '点击选中按钮，再次按下拖拽排序',
                        bg: '#8741d7',
                        act: 'del'
                    }
                ]
            }
            builder.btns(sData.btns);
        });


        $g('tab_label').keyup(function () {
            let {t, d} = $selTab();
            d.label = this.value;
            t.find('>span').html(this.value||'Tab标题');
        });
        $g('tabTitle').keyup(function () {
            sData.tabTitle = this.value;
            if (sData.tabPos === 2) {
                $g('topTab').html(!this.value ? '' : '<div id="vitabThis_' + args.uid + '"><span>' + sData.tabTitle + '</span>：</div>');
            }else{
                $g('vitabThis').find('>span').html(this.value||'基本信息');
            }
        });
        selectOn('tab_type', function (o) {
            let {d} = $selTab();
            d.type = parseInt(o.value);
            if (d.type === 2) {
                $gs(['tab_goUrlDiv'], ['tab_goPageIdDiv', 'tab_goPageParamDiv', 'tab_goPageFilterDiv']);
            } else {
                $gs(['tab_goPageIdDiv', 'tab_goPageParamDiv', 'tab_goPageFilterDiv'], ['tab_goUrlDiv']);
            }
        });
        selectOn('tab_goPageId', function (o) {
            let {d} = $selTab();
            d.goPageId = o.value;
        });
        $g('tab_goPageParam').keyup(function () {
            let {d} = $selTab();
            d.goPageParam = this.value;
        });
        $g('tab_goPageFilter').keyup(function () {
            let {d} = $selTab();
            d.goPageFilter = this.value;
        });
        $g('tab_goUrl').keyup(function () {
            let {d} = $selTab();
            d.goUrl = this.value;
        });
        $g('sqlFilter').blur(function () {
            sData.sqlFilter = this.value;
        });
        selectOn('pageHandler', function (o) {
            sData.pageHandler = o.value;
        });

        $g('headTips').keyup(function () {
            if (this.value !== '') {
                $g('headTipsBlock').html(this.value).show();
            } else {
                $g('headTipsBlock').html('').hide();
            }
            sData.headTips = $g('headTipsBlock').html();
        });
        $g('footTips').keyup(function () {
            if (this.value !== '') {
                $g('footTipsBlock').html(this.value).show();
            } else {
                $g('footTipsBlock').html('').hide();
            }
            sData.footTips = $g('footTipsBlock').html();
        });
        $('.pageTips').click(function () {
            canvas.find('.jdiy-selected').removeClass('jdiy-selected');
            layui.element.tabChange('rtTab_' + args.uid, 'rtTab2_' + args.uid);
        });

        $g('inDesignReset').click(function () {
            layui.layer.confirm('此操作将撤销您对本页面所做的所有更改，确定要这样做吗？', function (index) {
                layui.layer.close(index);
                reset(null, canvas.find('.jdiy-selected').attr('id'));
                layui.layer.msg('已撤销还原!');
            });
        });

        $g('inDesignSave').click(function () {
            save();
        });

        $(rtForm).find('.jdiy-form-help').click(function () {
            let ui = 'view', help = $(this).data('help'),
                helpMe = (h) => typeof h == 'object' ? layer.open(h) : layer.tips(h, '.jdev-prop-' + help + args.uid, {
                    tips: [4, '#FF5722'],
                    time: 10000
                });
            help && layui.jdhp && layui.jdhp[ui] && layui.jdhp[ui][help] &&
            helpMe(
                typeof layui.jdhp[ui][help] == 'function'
                    ? layui.jdhp[ui][help](args.uid)
                    : layui.jdhp[ui][help]
            );
        });

        reset();
    }

    exports('viewDesign', {
        render: design_vi_main
    });
});